package com.le.tester.dao;

import com.le.tester.dto.GoodsStockDto;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * createTime：2024-11-28 15:37
 * description：库存扣减dao
 */
@Mapper
public interface StockDao {
    @Select("select stock from goods_stock where goods_id = #{goodsId}")
    long selectStockByGoodsId(@Param("goodsId") Long goodsId);

    @Update("update goods_stock set stock = #{stock} where goods_id = #{goodsId}")
    int updateStockByGoodsId(@Param("stock") Long stock, @Param("goodsId") Long goodsId);

    @Update("update goods_stock set stock = stock - #{count} where goods_id = #{goodsId} and stock >= #{count}")
    int updateStockByGoodsIdOne(@Param("goodsId") Long goodsId, @Param("count") Integer count);

    @Select("select stock from goods_stock where goods_id = #{goodsId} for update")
    long selectStockByGoodsIdForUpdate(@Param("goodsId") Long goodsId);


    @Select("select stock,version from goods_stock where goods_id = #{goodsId}")
    List<GoodsStockDto> selectStockInfoByGoodsId(@Param("goodsId") Long goodsId);

    @Update("update goods_stock set stock = #{stock},version = #{version} + 1 where goods_id = #{goodsId} and version = #{version}")
    int updateStockByGoodsIdCAS(@Param("stock") Long stock, @Param("goodsId") Long goodsId, @Param("version") Integer version);
}
